﻿#include "XQAnimationButton.h"
#include <QPainter>
#include <QPaintEvent>
void XQAnimationButton::paintEvent(QPaintEvent* event)
{
    if (m_pixmatps[int(mouseState::mouseLeave)].isNull())
        return QPushButton::paintEvent(event);
    QPainter painter(this);
    // 计算绘制区域和缩放比例
    QRectF target(0, 0, width(), height());
    QRectF source(0, 0, m_pixmatps[int(m_State)].width(), m_pixmatps[int(m_State)].height());
    qreal aspectRatio = qMin(target.width() / source.width(), target.height() / source.height());
    QRectF centeredRect((target.width() - aspectRatio * source.width()) / 2.0 + target.x(),
        (target.height() - aspectRatio * source.height()) / 2.0 + target.y(),
        aspectRatio * source.width(),
        aspectRatio * source.height());

    if (isEnabled() == false)
    {
        painter.drawPixmap(event->rect(), m_pixmatps[int(mouseState::buttonForbidden)]);
        Bubble_hide();
        m_State = mouseState::mouseLeave;
    }
    else
    {
        painter.drawPixmap(centeredRect.toRect(), m_pixmatps[int(m_State)]);
    }

}

void XQAnimationButton::enterEvent(QEnterEvent* event)
{
    if (isEnabled() == false)
        return;
    if (!m_pixmatps[int(mouseState::mouseEnter)].isNull())
    {
        m_State = mouseState::mouseEnter;
    }
    else
        m_State = mouseState::mouseLeave;
    update();
    if(m_BubbleEnabled)
        Bubble_show(m_BubbleText, mapToGlobal(QPoint(0, 0)));
    QPushButton::enterEvent(event);
}

void XQAnimationButton::leaveEvent(QEvent* event)
{
    if (isEnabled() == false)
        return;
    if (!m_pixmatps[int(mouseState::mouseLeave)].isNull())
    {
        m_State = mouseState::mouseLeave;
        update();
    }
    Bubble_hide();
    QPushButton::leaveEvent(event);
}

void XQAnimationButton::mousePressEvent(QMouseEvent* event)
{
    if (isEnabled() == false)
        return;
    if (event->button() == Qt::LeftButton)
    {
        if (!m_pixmatps[int(mouseState::mousePress)].isNull())
        {
            m_State = mouseState::mousePress;
            update();
        }
    }
    QPushButton::mousePressEvent(event);
}

void XQAnimationButton::mouseReleaseEvent(QMouseEvent* event)
{
    if (isEnabled() == false)
        return;
    if (event->button() == Qt::LeftButton)
    {
        if (!m_pixmatps[int(mouseState::mouseRelease)].isNull())
        {
            m_State = mouseState::mouseRelease;
            update();
        }
    }
    QPushButton::mouseReleaseEvent(event);
}

void XQAnimationButton::contextMenuEvent(QContextMenuEvent* event)
{
    emit contextMenu();
}
